package org.dwell.urlfilter.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.dwell.urlfilter.demo.exception.EmptyAccountException;
import org.dwell.urlfilter.demo.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Jange on 2016/4/6.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(String username, String password) {
        if(username == null || "".equals(username)){
            return Result.error("用户名不能为空");
        }

        if(password == null || "".equals(password)){
            return Result.error("密码不能为空");
        }

        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //执行login方法，跳转到自己定义的Realm的doGetAuthenticationInfo去验证身份
            user.login(token);
        }catch(EmptyAccountException ae){
            user.getSession().setAttribute("message", "用户名不能为空");
            token.clear();
            return Result.error("用户名不能为空");
        }catch(UnknownAccountException uae){
            user.getSession().setAttribute("message", "用户不存在");
            token.clear();
            return Result.error("用户不存在");
        }catch(IncorrectCredentialsException ice){
            user.getSession().setAttribute("message", "用户名/密码错误");
            token.clear();
            return Result.error("用户名/密码错误");
        }catch(LockedAccountException lae){
            user.getSession().setAttribute("message", "账户被冻结");
            token.clear();
            return Result.error("账户已被冻结");
        }catch (AuthenticationException e) {
            user.getSession().setAttribute("message", e);
            token.clear();
            return Result.error("登录失败 ~ " + e.getMessage());
        }
        return Result.ok("login succeed!");
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        Subject user = SecurityUtils.getSubject();
        user.logout();
        return "redirect:/";
    }
}
